<template>
  <!--  搜索框组件-->
  <TableSearch
    :deletSome="deletSomes"
    @deletSome="deletSomeUsers"
    :search-fields="searchFields"
    @addRow="addUser"
    @search="handleSearch"
    @reset="handleReset"
  ></TableSearch>
  <!-- 表格组件 -->
  <TableComponent
    :columns="columns"
    :tableData="tableData"
    :loading="loading"
    :deletSome="deletSomes"
    @delete="handleDelete"
    @edit="editUserRow"
    @somedelete="handleSomeDelete"
  />
  <pagination
    :current-page="currentPage"
    :page-size="pageSize"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  ></pagination>

  
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'

import pagination from '@/components/pagination/index.vue'
import TableSearch from '@/components/TableSearch/teachersearch.vue'
import TableComponent from '@/components/DataTable/teachertable.vue'

import api from '@/api/teacher'
import router from '@/router/index.js'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'

// 侧边栏折叠状态
const sidebarCollapsed = ref(false)

let deletSomes = true
// 搜索字段
const searchFields = reactive([
  { label: '用户名', prop: 'teacherName', type: 'input' },
  { label: '手机号码', prop: 'telephone', type: 'input' },
  {
    label: '权限',
    prop: 'role',
    type: 'select',
    options: [
      { label: '超级管理员', value: '1' },
      { label: '讲师', value: '2' },
    ],
  },
  // { label: '注册时间', prop: 'createTime', type: 'date-range' },
])

// 表格列定义
const columns = [
  { prop: 'teacherId', label: '序号', width: 80, headerAlign: 'center' },
  // { prop: 'imgPath', label: '头像', width: 120, headerAlign: 'center' },
  { prop: 'teacherName', label: '姓名', width: 120, headerAlign: 'center' },
  { prop: 'trole.troleName', label: '权限', width: 120, headerAlign: 'center' },
  { prop: 'password', label: '密码', width: 120, headerAlign: 'center' },
  { prop: 'telephone', label: '手机号码', width: 180, headerAlign: 'center' },
  { prop: 'createTime', label: '创建时间', width: 300, headerAlign: 'center' },
  { prop: 'amendTime', label: '修改时间', width: 300, headerAlign: 'center' },
  // { prop: 'action', label: '操作', width: 180, fixed: 'right' },
]

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
let users
const Search = ref({})
// 加载表格数据
const loadData = async () => {
  loading.value = true

  try {
    Search.value.pageNum = currentPage.value
    Search.value.pageSize = pageSize.value

    // const response = await api.selectAll(Search.value);
    const response = await api.selectAllT(Search.value)
    console.log('老师列表' + response.data)

    tableData.value = response.data.list || []
    total.value = response.data.total || 0
    console.log('加载数据成功:', response)
    if (response.code == 200) {
      // 开发环境调试日志
    } else {
      // API返回了错误码
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    // 友好的错误提示
    ElMessage.error({
      message: error.message || '加载数据失败，请稍后重试',
      duration: 3000,
    })

    // 重置数据防止显示旧数据
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}
function addUser() {
  router.push(`/teacher/create`)
}
// 批量删除
async function deletSomeUsers() {
  try {
    // 确认对话框
    const confirmResult = await ElMessageBox.confirm(
      '确定要批量删除这些用户吗？此操作不可撤销！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    if (confirmResult !== 'confirm') {
      return // 用户点击了取消
    }

    // 极速模式：所有删除请求同时发起
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在批量删除用户...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    const results = await Promise.allSettled(
      Object.values(users).map((teacher) =>
        api
          .deletUser({ teacherId: teacher.teacherId })
          .then(() => ({ status: 'fulfilled', teacherId: teacher.teacherId }))
          .catch((error) => ({ status: 'rejected', teacherId: teacher.teacherId, error })),
      ),
    )

    // 关闭加载动画
    loadingInstance.close()

    // 生成统计报告
    const successCount = results.filter((r) => r.status === 'fulfilled').length
    const failedCount = results.filter((r) => r.status === 'rejected').length

    // 刷新数据
    await loadData()

    // 显示操作结果
    if (failedCount === 0) {
      ElMessage.success(`成功删除 ${successCount} 个用户`)
    } else if (successCount === 0) {
      ElMessage.error(`删除失败，所有 ${failedCount} 个用户均未删除成功`)
    } else {
      ElMessage.warning(`删除完成，成功 ${successCount} 个，失败 ${failedCount} 个`, {
        duration: 5000,
      })
    }

    return {
      total: results.length,
      success: successCount,
      failed: failedCount,
      errors: results
        .filter((r) => r.status === 'rejected')
        .map((r) => ({
          userId: r.userId,
          error: r.error.message,
        })),
    }
  } catch (error) {
    // 用户可能点击了取消按钮，不需要处理
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error(`删除操作出错: ${error.message}`)
    }
    return null
  }
}

function editUserRow(row) {
  router.push(`/teacher/${row.teacherId}/edit`)
  // sessionStorage.setItem("user",JSON);
}
// 处理搜索
const handleSearch = (params) => {
  console.log('Search params:', params)
  currentPage.value = 1
  Search.value = params
  loadData()
}

// 处理重置
const handleReset = () => {
  Search.value = {}
  currentPage.value = 1
  loadData()
}

// 删除功能
const handleDelete = async (row) => {
  // 极速模式：所有删除请求同时发起
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.teacherName}" (ID: ${row.teacherId}) 吗？`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false, // 防止误点
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            try {
              const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在删除用户...',
                background: 'rgba(0, 0, 0, 0.7)',
              })

              await api.deletUser({ teacherId: row.teacherId })
              done()
              // 关闭加载动画
              loadingInstance.close()
            } catch (error) {
              instance.confirmButtonLoading = false
              // 关闭加载动画
              loadingInstance.close()
              throw error
            }
          } else {
            done()
          }
        },
      },
    )

    // 删除成功后刷新数据
    await loadData()

    ElMessage({
      type: 'success',
      message: `用户 "${row.teacherName}" 删除成功`,
      duration: 3000,
    })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: `删除失败: ${error.message || '未知错误'}`,
        duration: 5000,
      })
    } else {
      ElMessage({
        type: 'info',
        message: '已取消删除操作',
        duration: 2000,
      })
    }
  }
}
function handleSomeDelete(rows) {
  users = rows
  console.log(rows, '获取多列的值')
}
// 处理每页数量变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadData()
}

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadData()
}
function deleteclick() {}
// 初始化加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
#app {
  font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
  min-height: 100vh;
}
</style>
